<template>
  <AppLayout>
    <!-- 顶部筛选栏 -->
    <PostFilterBar @filterChange="handleFilterChange" />

    <!-- 帖子列表 -->
    <div class="space-y-4">
      <PostCard v-for="post in posts" :key="post.id" :post="post" />
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="text-center py-8">
      <div
        class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-primary border-t-transparent"
      ></div>
      <p class="mt-2 text-gray-600">加载中...</p>
    </div>

    <!-- 空状态 -->
    <div
      v-else-if="posts.length === 0 && !isLoading"
      class="text-center py-12 bg-white rounded-xl shadow-sm"
    >
      <i class="fa fa-folder-open-o text-4xl text-gray-300 mb-3"></i>
      <p class="text-gray-500">暂无帖子</p>
    </div>

    <!-- 加载更多指示器（用于滚动自动加载） -->
    <div v-else-if="hasMore" class="relative py-8">
      <div ref="loadingTrigger" class="w-full h-1"></div>
      <div v-if="isLoadingMore" class="text-center">
        <div
          class="inline-block animate-spin rounded-full h-6 w-6 border-4 border-primary border-t-transparent mb-2"
        ></div>
        <p class="text-gray-500 text-sm">加载中...</p>
      </div>
    </div>

    <!-- 到底了提示 -->
    <div
      v-else-if="posts.length > 0 && !hasMore"
      class="text-center py-8 text-gray-500"
    >
      <i class="fa fa-check-circle mb-2"></i>
      <p>已加载全部内容</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="text-center py-4">
      <p class="text-red-500 flex items-center justify-center gap-2">
        <i class="fa fa-exclamation-circle"></i>
        {{ errorMessage }}
      </p>
      <button class="mt-2 text-primary hover:underline" @click="loadPosts()">
        重试
      </button>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue"
import { useRouter } from "vue-router"
import PostCard from "./PostCard.vue"
import PostFilterBar from "./layout/PostFilterBar.vue"
import AppLayout from "./layout/AppLayout.vue"
import { getPosts, type Post } from "../services/postService"
import { isLoggedIn } from "../services/userService"

// 状态管理
const posts = ref<Post[]>([])
const isLoading = ref(false)
const isLoadingMore = ref(false)
const errorMessage = ref("")
const lastId = ref<number | null>(null)
const hasMore = ref(true)
const loadingTrigger = ref<HTMLElement | null>(null)
const currentFilter = ref({
  sort: "latest",
  category: null as number | null,
})
const router = useRouter()

// 加载帖子列表
const loadPosts = async (reset: boolean = false) => {
  try {
    if (reset) {
      posts.value = []
      lastId.value = null
    }

    isLoading.value = true
    errorMessage.value = ""

    // 修复：使用明确的类型定义替代any
    const params: {
      size: number
      lastId?: number
      cateId?: number
    } = {
      size: 5, // 一次查询5条
    }

    // 添加分类筛选
    if (currentFilter.value.category) {
      params.cateId = currentFilter.value.category
    }

    // 添加分页参数
    if (lastId.value !== null) {
      params.lastId = lastId.value
    }

    // 获取数据
    const data = await getPosts(params)
    console.log(data)

    // 关键修复：根据postService.ts调整数据处理逻辑
    if (data && data.data && Array.isArray(data.data.postRespDTOList)) {
      // 处理API返回的数据
      const processedPosts = data.data.postRespDTOList.map(
        (post): Post => ({
          // 保留原始数据的所有字段
          ...post,
          // 确保user对象存在
          user: post.user
            ? {
                ...post.user,
                // 清理头像URL并提供默认值
                avatar: post.user.avatar
                  ? post.user.avatar.replace(/`/g, "").trim()
                  : "https://picsum.photos/seed/user/60/60",
                // 处理昵称，确保不为空
                nickname: post.user.nickname || post.user.loginId || "匿名用户",
              }
            : {
                // 为无user信息的帖子提供默认用户对象
                uid: 0,
                loginId: "anonymous",
                nickname: "匿名用户",
                avatar: "https://picsum.photos/seed/user/60/60",
                intro: "",
              },
          // 清理媒体URL
          media: post.media
            ? post.media.map((url: string) => url.replace(/`/g, "").trim())
            : [],
          // 确保所有必要字段都有默认值
          title: post.title || "无标题",
          content: post.content || "无内容",
          readCount: post.readCount || 0,
          commentCount: post.commentCount || 0,
          likeCount: post.likeCount || 0,
          // 确保布尔类型字段有正确的默认值
          liked: !!post.liked,
          collected: !!post.collected,
          canEdit: !!post.canEdit,
          canDelete: !!post.canDelete,
        })
      )

      // 更新帖子列表
      if (reset) {
        posts.value = processedPosts
      } else {
        posts.value = [...posts.value, ...processedPosts]
      }

      // 更新分页信息
      if (processedPosts.length > 0) {
        lastId.value = processedPosts[processedPosts.length - 1].id ?? null
        hasMore.value = processedPosts.length >= params.size
      } else {
        hasMore.value = false
      }
    } else {
      // 如果API返回为空，使用模拟数据
      if (posts.value.length === 0) {
        posts.value = getMockPosts()
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error("获取帖子列表失败:", error)
    errorMessage.value = "获取帖子失败，请稍后重试"

    // 出错时也使用模拟数据
    if (posts.value.length === 0) {
      posts.value = getMockPosts()
    }
  } finally {
    isLoading.value = false
  }
}

// 同时，确保onMounted中能够正常加载数据
onMounted(() => {
  // 如果您确认登录状态没问题，可以保留登录检查
  // 如果想直接测试帖子显示，可以临时注释登录检查
  if (!isLoggedIn()) {
    router.push("/login")
    return
  }

  loadPosts()
  setupScrollListener()
})

// 加载更多帖子
const loadMorePosts = async () => {
  if (isLoadingMore.value || !hasMore.value) return

  try {
    isLoadingMore.value = true
    await loadPosts(false)
  } catch (error) {
    console.error("加载更多帖子失败:", error)
    errorMessage.value = "加载更多失败，请稍后重试"
  } finally {
    isLoadingMore.value = false
  }
}

// 滚动加载的处理函数
const handleScroll = () => {
  // 计算滚动相关值
  const scrollTop =
    window.scrollY ||
    document.documentElement.scrollTop ||
    document.body.scrollTop
  const viewportHeight =
    window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight
  const scrollHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight

  // 当滚动到页面底部附近时触发加载
  if (
    scrollTop + viewportHeight >= scrollHeight - 100 &&
    hasMore.value &&
    !isLoadingMore.value
  ) {
    loadMorePosts()
  }
}

// 设置滚动事件监听
const setupScrollListener = () => {
  // 添加滚动事件监听
  window.addEventListener("scroll", handleScroll)

  // 在组件卸载时清理事件监听
  onUnmounted(() => {
    window.removeEventListener("scroll", handleScroll)
  })
}

// 处理筛选条件变化
const handleFilterChange = (payload: {
  sort: string
  category: number | null
}) => {
  currentFilter.value = payload
  loadPosts(true)
}

// 获取模拟帖子数据
const getMockPosts = (): Post[] => {
  return [
    {
      id: 1,
      uid: 1,
      cateId: 4,
      cateName: "技术讨论",
      title: "Tailwind CSS v3 新特性全面解析",
      content:
        "Tailwind CSS v3带来了许多令人兴奋的新特性，包括JIT编译模式、原生字体大小调整、颜色不透明度工具类等。本文将深入探讨这些新特性，并提供实用的代码示例，帮助你更好地利用Tailwind CSS提升开发效率。",
      media: ["https://picsum.photos/seed/tailwind/800/400"],
      readCount: 128,
      commentCount: 42,
      likeCount: 128,
      collectionCount: 0,
      postTop: 0,
      createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
      user: {
        uid: 1,
        loginId: "user1",
        nickname: "李四",
        avatar: "https://picsum.photos/seed/user2/50/50",
        intro: "前端开发工程师",
      },
      canEdit: false,
      canDelete: false,
      liked: false,
      collected: false,
    },
    {
      id: 2,
      uid: 2,
      cateId: 3,
      cateName: "生活分享",
      title: "我用三个月时间学习前端开发的心得体会",
      content:
        "作为一名零基础的学习者，我在三个月内从HTML、CSS和JavaScript的基础开始，逐步掌握了前端开发的核心技能。这篇文章分享了我的学习方法、遇到的挑战以及如何克服它们的经验，希望能对正在学习前端的朋友有所帮助。",
      media: [
        "https://picsum.photos/seed/study1/400/300",
        "https://picsum.photos/seed/study2/400/300",
      ],
      readCount: 256,
      commentCount: 89,
      likeCount: 256,
      collectionCount: 0,
      postTop: 0,
      createTime: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString(),
      user: {
        uid: 2,
        loginId: "user2",
        nickname: "王五",
        avatar: "https://picsum.photos/seed/user3/50/50",
        intro: "前端学习者",
      },
      canEdit: false,
      canDelete: false,
      liked: false,
      collected: false,
    },
    {
      id: 3,
      uid: 3,
      cateId: 5,
      cateName: "问答求助",
      title: "如何优化大型React应用的性能？",
      content:
        "我们团队正在开发一个大型React应用，随着功能的增加，应用的性能逐渐下降，特别是在低配置设备上。请问有哪些实用的优化技巧可以显著提升React应用的性能？已经尝试过组件懒加载，但效果不明显。",
      media: [],
      readCount: 78,
      commentCount: 64,
      likeCount: 78,
      collectionCount: 0,
      postTop: 0,
      createTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
      user: {
        uid: 3,
        loginId: "user3",
        nickname: "赵六",
        avatar: "https://picsum.photos/seed/user4/50/50",
        intro: "React开发者",
      },
      canEdit: false,
      canDelete: false,
      liked: false,
      collected: false,
    },
  ]
}
</script>

<style scoped>
/* 组件特定样式 */
</style>
